'use strict';

angular.module('webpageApp')

.filter('formatTpl', [function() {
  return function(set, base) {
    return formatSet(set, undefined);
  };
}]);

var excludePath = function(childPath, parentPath) {
  if (childPath == undefined) return '';
  if (parentPath == undefined || parentPath.length == 0) return childPath;
  if (childPath.length <= parentPath.length) return '';
  if (childPath.indexOf(parentPath) == 0) {
    var temp = childPath.slice(parentPath.length);
    // console.log(childPath, 'childPath');
    var arr = temp.split(' > ');
    arr.splice(0, 1);
    console.log(arr, 'arr');
    return arr.join(' > ');
  }
  return childPath;
};

var formatRule = function(set, parentPath) {
  var expr = excludePath(set.path, parentPath);
  var rule = {
    name: set.name,
    mode: 'css',
    target: (set.children.length) > 0 ? '' : 'text',
    expression: expr == '' && set.children.length >
      0 ? 'body' : expr,
    list: []
  }
  return rule;
}

var formatSet = function(set, parentPath) {
  var obj = formatRule(set, parentPath);
  console.log(obj, 'obj');
  var child = set.children;
  for (var i = 0; i < child.length; i++) {
    obj.list.push(formatSet(child[i], set.path));
  }
  console.log(set, 'sssssset');
  // console.log(obj, 'setssss');
  return obj;
};
